ASP.NET MVC 4 Recipes by John Ciliberti

ASP.NET MVC 4 Recipes by John Ciliberti

Author:John Ciliberti
Language: eng
Format: epub, pdf
ISBN: 9781430247739
Publisher: Apress


Listing 8-4. Using WhenAll with an IEnumerible

public async Task<ActionResult> CallTenServicesAsync()

{

List<Task<byte[]>> dataTasks = new List<Task<byte[]>>();

for (int i = 0; i < 10; i++)

{

using (WebClient webClient = new WebClient())

{

Uri uri = new Uri(string.Format(webserviceURL, i));

dataTasks.Add(webClient.DownloadDataTaskAsync(uri));

}

}

byte[][] allBytes = await Task.WhenAll(dataTasks);

ViewBag.totalLength = allBytes.Sum(w => w.Length);

return View();

}

Looking at Listings 8-3 and 8-4, you have probably noticed that all the Tasks passed to Task.WhenAll are of the same type. This is a requirement. If you attempt to pass in mixed types, the code will not compile. This is somewhat inconvenient. Since you are calling out to several services, it is likely that they will have different return types.

There are a few strategies that you can use to get around this. The first would be like in Listing 8-3, where the code is calling a RESTful web service and receiving the results as a JSON-encoded string. After the I/O operations are complete, you can then use a JSON serializer such as the one in Newtonsoft.Json to convert the JSON text into C# objects. Another strategy would be use an IEnumerable<Task> rather than a Task of a certain return type. In this case, you will not be able to pass the results of the await operation directly into an array, as in Listings 8-3 and 8-4. You will instead need to cast the results for each operation as shown in Listing 8-5.



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.